﻿<script lang="ts" setup name="planList">
import { ref, reactive, onMounted } from 'vue';
import { auth } from '/@/utils/authFunction';
import { ElMessageBox, ElMessage } from 'element-plus';
import { downloadStreamFile } from '/@/utils/download';
import { usePlanListApi } from '/@/api/plans/planList';
import { usePlanTypeApi } from '/@/api/plans/planType';
import { getAPI } from '/@/utils/axios-utils';
import { SysOrgApi } from '/@/api-services/api';
import { SysOrg } from '/@/api-services/models';
import editDialog from '/@/views/plans/planList/component/editDialog.vue';
import printDialog from '/@/views/system/print/component/hiprint/preview.vue';
import ModifyRecord from '/@/components/table/modifyRecord.vue';
import ImportData from '/@/components/table/importData.vue';
import InlineEdit from '/@/views/plans/planList/component/InlineEdit.vue';

const planListApi = usePlanListApi();
const planTypeApi = usePlanTypeApi();
const printDialogRef = ref();
const editDialogRef = ref();
const importDataRef = ref();
interface TableDataItem {
	id: number;
	ch: string;
	fd: string;
	className: number;
	classNameFkDisplayName: string;
	workAreaId: number;
	workAreaFkDisplayName: string;
	team: string;
	planStart: string;
	planEnd: string;
	actualStart: string | null;
	actualEnd: string | null;
	startDelayDays: number;
	endDelayDays: number;
	startDelayReason: string | null;
	endDelayReason: string | null;
	status: number;
	remark: string | null;
}

const state = reactive({
	exportLoading: false,
	tableLoading: false,
	stores: {},
	showAdvanceQueryUI: false,
	dropdownData: {} as any,
	selectData: [] as TableDataItem[],
	tableQueryParams: {
		status: 0,
	} as any,
	tableParams: {
		page: 1,
		pageSize: 20,
		total: 0,
		field: 'createTime', // 默认的排序字段
		order: 'descending', // 排序方向
		descStr: 'descending', // 降序排序的关键字符
	},
	tableData: [] as TableDataItem[],
	// 行内编辑状态管理
	inlineEditLoading: {} as Record<string, boolean>,
});

// 延期原因编辑状态管理
const delayReasonEdit = reactive({
	start: {} as Record<string, string>,
	end: {} as Record<string, string>,
});

// 页面加载时
onMounted(async () => {
	// 获取计划清单下拉数据
	// const data = (await planListApi.getDropdownData(true).then((res) => res.data.result)) ?? {};

	// 从计划分类API获取分类数据
	const planTypeData = await planTypeApi.page({ page: 1, pageSize: 99999999 }).then((res) => res.data.result);
	state.dropdownData.className =
		planTypeData?.items?.map((item: any) => ({
			value: item.id,
			label: item.name,
		})) ?? [];

	// 从系统组织API获取区域数据
	const orgData = await getAPI(SysOrgApi)
		.apiSysOrgListGet(0)
		.then((res) => res.data.result);

	// 递归提取所有组织节点（包括子节点），排除根节点
	const extractAllOrgs = (orgs: SysOrg[]): Array<{ value: string; label: string }> => {
		const result: Array<{ value: string; label: string }> = [];
		orgs.forEach((org) => {
			// 跳过根节点（制造部），只处理子节点
			if (org.children && org.children.length > 0) {
				// 递归处理子节点
				result.push(...extractAllOrgs(org.children));
			} else {
				// 如果是叶子节点，直接添加
				result.push({
					value: org.id?.toString() || '',
					label: org.name || '',
				});
			}
		});
		return result;
	};

	state.dropdownData.workAreaId = extractAllOrgs(orgData || []);

	// console.log('分类下拉数据', state.dropdownData.className);
	// console.log('区域下拉数据', state.dropdownData.workAreaId);
});

// 查询操作
const handleQuery = async (params: any = {}) => {
	state.tableLoading = true;
	state.tableParams = Object.assign(state.tableParams, params);
	const result = await planListApi.page(Object.assign(state.tableQueryParams, state.tableParams)).then((res) => res.data.result);
	state.tableParams.total = result?.total;
	state.tableData = (result?.items ?? []) as TableDataItem[];
	
	// 初始化延期原因编辑状态
	state.tableData.forEach((item) => {
		delayReasonEdit.start[item.id] = item.startDelayReason || '';
		delayReasonEdit.end[item.id] = item.endDelayReason || '';
	});
	
	state.tableLoading = false;
};

// 列排序
const sortChange = async (column: any) => {
	state.tableParams.field = column.prop;
	state.tableParams.order = column.order;
	await handleQuery();
};

// 删除
const delPlanList = (row: any) => {
	ElMessageBox.confirm(`确定要删除吗?`, '提示', {
		confirmButtonText: '确定',
		cancelButtonText: '取消',
		type: 'warning',
	})
		.then(async () => {
			await planListApi.delete({ id: row.id });
			handleQuery();
			ElMessage.success('删除成功');
		})
		.catch(() => {});
};

// 批量删除
const batchDelPlanList = () => {
	ElMessageBox.confirm(`确定要删除${state.selectData.length}条记录吗?`, '提示', {
		confirmButtonText: '确定',
		cancelButtonText: '取消',
		type: 'warning',
	})
		.then(async () => {
			await planListApi.batchDelete(state.selectData.map((u: { id: any }) => ({ id: u.id }))).then((res) => {
				ElMessage.success(`成功批量删除${res.data.result}条记录`);
				handleQuery();
			});
		})
		.catch(() => {});
};

// 导出数据
const exportPlanListCommand = async (command: string) => {
	try {
		state.exportLoading = true;
		if (command === 'select') {
			const params = Object.assign({}, state.tableQueryParams, state.tableParams, { selectKeyList: state.selectData.map((u: { id: any }) => u.id) });
			await planListApi.exportData(params).then((res) => downloadStreamFile(res));
		} else if (command === 'current') {
			const params = Object.assign({}, state.tableQueryParams, state.tableParams);
			await planListApi.exportData(params).then((res) => downloadStreamFile(res));
		} else if (command === 'all') {
			const params = Object.assign({}, state.tableQueryParams, state.tableParams, { page: 1, pageSize: 99999999 });
			await planListApi.exportData(params).then((res) => downloadStreamFile(res));
		}
	} finally {
		state.exportLoading = false;
	}
};

// 只取前10位，假设格式为YYYY-MM-DD HH:mm:ss
const formatDate = (row: any, column: any, cellValue: string) => {
	if (!cellValue) return '';
	return cellValue.slice(0, 10);
};

// 更新延期原因
const updateDelayReason = async (id: number, field: string, reason: string) => {
	try {
		await planListApi.updateDelayReason(id, field, reason);
		
		// 更新本地数据
		const row = state.tableData.find((item) => item.id === id);
		if (row) {
			if (field === 'StartDelayReason') {
				row.startDelayReason = reason;
			} else if (field === 'EndDelayReason') {
				row.endDelayReason = reason;
			}
		}
		
		ElMessage.success('延期原因更新成功');
	} catch (error) {
		console.error('更新延期原因失败:', error);
		ElMessage.error('更新延期原因失败');
	}
};

// 行内编辑更新方法
const updateInlineField = async (row: any, field: string, value: string | null) => {
	const loadingKey = `${row.id}_${field}`;
	state.inlineEditLoading[loadingKey] = true;

	try {
		// 准备更新数据 - 发送完整的行数据以满足后端验证要求
		const updateData = {
			id: row.id,
			ch: row.ch,
			fd: row.fd,
			className: row.className,
			workAreaId: row.workAreaId,
			team: row.team,
			planStart: row.planStart,
			planEnd: row.planEnd,
			actualStart: row.actualStart,
			actualEnd: row.actualEnd,
			remark: row.remark,
			status: row.status,
			// 更新指定字段的值
			[field]: value,
		};

		// 调用更新API
		const result = await planListApi.update(updateData);

		// 更新本地数据 - 如果后端返回了更新后的数据，使用返回的数据
		if (result.data && result.data.result) {
			// 使用后端返回的完整数据更新本地行数据
			Object.assign(row, result.data.result);
		} else {
			// 如果没有返回完整数据，至少更新编辑的字段
			row[field] = value;

			// 如果是编辑实际完工字段，可能需要刷新数据以获取最新状态
			if (field === 'actualEnd') {
				// 刷新表格数据以获取后端自动更新的状态
				handleQuery();
			}
		}

		ElMessage.success('更新成功');
	} catch (error) {
		console.error('更新失败:', error);
		ElMessage.error('更新失败，请稍后重试');
	} finally {
		state.inlineEditLoading[loadingKey] = false;
	}
};

handleQuery();
</script>
<template>
	<div class="planList-container" v-loading="state.exportLoading">
		<el-card shadow="hover" :body-style="{ paddingBottom: '0' }">
			<el-form :model="state.tableQueryParams" ref="queryForm" labelWidth="90">
				<el-row>
					<el-col :xs="24" :sm="12" :md="12" :lg="8" :xl="4" class="mb10">
						<el-form-item label="关键字">
							<el-input v-model="state.tableQueryParams.keyword" clearable placeholder="请输入模糊查询关键字" />
						</el-form-item>
					</el-col>
					<el-col :xs="24" :sm="12" :md="12" :lg="8" :xl="4" class="mb10" v-if="state.showAdvanceQueryUI">
						<el-form-item label="船号">
							<el-input v-model="state.tableQueryParams.ch" clearable placeholder="请输入船号" />
						</el-form-item>
					</el-col>
					<el-col :xs="24" :sm="12" :md="12" :lg="8" :xl="4" class="mb10" v-if="state.showAdvanceQueryUI">
						<el-form-item label="分段">
							<el-input v-model="state.tableQueryParams.fd" clearable placeholder="请输入分段" />
						</el-form-item>
					</el-col>
					<el-col :xs="24" :sm="12" :md="12" :lg="8" :xl="4" class="mb10" v-if="state.showAdvanceQueryUI">
						<el-form-item label="分类">
							<el-select clearable filterable v-model="state.tableQueryParams.className" placeholder="请选择分类">
								<el-option v-for="(item, index) in state.dropdownData.className ?? []" :key="index" :value="item.value" :label="item.label" />
							</el-select>
						</el-form-item>
					</el-col>
					<el-col :xs="24" :sm="12" :md="12" :lg="8" :xl="4" class="mb10" v-if="state.showAdvanceQueryUI">
						<el-form-item label="区域">
							<el-select clearable filterable v-model="state.tableQueryParams.workAreaId" placeholder="请选择区域">
								<el-option v-for="(item, index) in state.dropdownData.workAreaId ?? []" :key="index" :value="item.value" :label="item.label" />
							</el-select>
						</el-form-item>
					</el-col>
					<el-col :xs="24" :sm="12" :md="12" :lg="8" :xl="4" class="mb10" v-if="state.showAdvanceQueryUI">
						<el-form-item label="劳务队">
							<el-input v-model="state.tableQueryParams.team" clearable placeholder="请输入劳务队" />
						</el-form-item>
					</el-col>
					<el-col :xs="24" :sm="12" :md="12" :lg="8" :xl="4" class="mb10" v-if="state.showAdvanceQueryUI">
						<el-form-item label="计划开工">
							<el-date-picker
								type="daterange"
								v-model="state.tableQueryParams.planStartRange"
								value-format="YYYY-MM-DD HH:mm:ss"
								start-placeholder="开始日期"
								end-placeholder="结束日期"
								:default-time="[new Date('1 00:00:00'), new Date('1 23:59:59')]"
							/>
						</el-form-item>
					</el-col>
					<el-col :xs="24" :sm="12" :md="12" :lg="8" :xl="4" class="mb10" v-if="state.showAdvanceQueryUI">
						<el-form-item label="计划完工">
							<el-date-picker
								type="daterange"
								v-model="state.tableQueryParams.planEndRange"
								value-format="YYYY-MM-DD HH:mm:ss"
								start-placeholder="开始日期"
								end-placeholder="结束日期"
								:default-time="[new Date('1 00:00:00'), new Date('1 23:59:59')]"
							/>
						</el-form-item>
					</el-col>
					<el-col :xs="24" :sm="12" :md="12" :lg="8" :xl="4" class="mb10" v-if="state.showAdvanceQueryUI">
						<el-form-item label="实际开工">
							<el-date-picker
								type="daterange"
								v-model="state.tableQueryParams.actualStartRange"
								value-format="YYYY-MM-DD HH:mm:ss"
								start-placeholder="开始日期"
								end-placeholder="结束日期"
								:default-time="[new Date('1 00:00:00'), new Date('1 23:59:59')]"
							/>
						</el-form-item>
					</el-col>
					<el-col :xs="24" :sm="12" :md="12" :lg="8" :xl="4" class="mb10" v-if="state.showAdvanceQueryUI">
						<el-form-item label="实际完工">
							<el-date-picker
								type="daterange"
								v-model="state.tableQueryParams.actualEndRange"
								value-format="YYYY-MM-DD HH:mm:ss"
								start-placeholder="开始日期"
								end-placeholder="结束日期"
								:default-time="[new Date('1 00:00:00'), new Date('1 23:59:59')]"
							/>
						</el-form-item>
					</el-col>
					<el-col :xs="24" :sm="12" :md="12" :lg="8" :xl="4" class="mb10" v-if="state.showAdvanceQueryUI">
						<el-form-item label="备注">
							<el-input v-model="state.tableQueryParams.remark" clearable placeholder="请输入备注" />
						</el-form-item>
					</el-col>
					<el-col :xs="24" :sm="12" :md="12" :lg="8" :xl="4" class="mb10" v-if="state.showAdvanceQueryUI">
						<el-form-item label="状态">
							<g-sys-dict v-model="state.tableQueryParams.status" code="FinishStatusEnum" render-as="select" placeholder="请选择状态" clearable filterable />
						</el-form-item>
					</el-col>
					<el-col :xs="24" :sm="12" :md="12" :lg="8" :xl="4" class="mb10">
						<el-form-item>
							<el-button-group style="display: flex; align-items: center">
								<el-button type="primary" icon="ele-Search" @click="handleQuery" v-auth="'planList:page'" v-reclick="1000"> 查询 </el-button>
								<el-button icon="ele-Refresh" @click="() => (state.tableQueryParams = {})"> 重置 </el-button>
								<el-button icon="ele-ZoomIn" @click="() => (state.showAdvanceQueryUI = true)" v-if="!state.showAdvanceQueryUI" style="margin-left: 5px"> 高级查询 </el-button>
								<el-button icon="ele-ZoomOut" @click="() => (state.showAdvanceQueryUI = false)" v-if="state.showAdvanceQueryUI" style="margin-left: 5px"> 隐藏 </el-button>
								<el-button type="danger" style="margin-left: 5px" icon="ele-Delete" @click="batchDelPlanList" :disabled="state.selectData.length == 0" v-auth="'planList:batchDelete'">
									删除
								</el-button>
								<el-button type="primary" style="margin-left: 5px" icon="ele-Plus" @click="editDialogRef.openDialog(null, '新增计划清单')" v-auth="'planList:add'"> 新增 </el-button>
								<el-dropdown :show-timeout="70" :hide-timeout="50" @command="exportPlanListCommand">
									<el-button type="primary" style="margin-left: 5px" icon="ele-FolderOpened" v-reclick="20000" v-auth="'planList:export'"> 导出 </el-button>
									<template #dropdown>
										<el-dropdown-menu>
											<el-dropdown-item command="select" :disabled="state.selectData.length == 0">导出选中</el-dropdown-item>
											<el-dropdown-item command="current">导出本页</el-dropdown-item>
											<el-dropdown-item command="all">导出全部</el-dropdown-item>
										</el-dropdown-menu>
									</template>
								</el-dropdown>
								<el-button type="warning" style="margin-left: 5px" icon="ele-MostlyCloudy" @click="importDataRef.openDialog()" v-auth="'planList:import'"> 导入 </el-button>
							</el-button-group>
						</el-form-item>
					</el-col>
				</el-row>
			</el-form>
		</el-card>
		<el-card class="full-table" shadow="hover" style="margin-top: 5px">
			<el-table
				:data="state.tableData"
				@selection-change="
					(val: any[]) => {
						state.selectData = val;
					}
				"
				style="width: 100%"
				v-loading="state.tableLoading"
				tooltip-effect="light"
				row-key="id"
				@sort-change="sortChange"
				border
			>
				<el-table-column type="selection" width="40" align="center" v-if="auth('planList:batchDelete') || auth('planList:export')" />
				<el-table-column type="index" label="序号" width="55" align="center" />
				<el-table-column prop="ch" label="船号" show-overflow-tooltip />
				<el-table-column prop="fd" label="分段" show-overflow-tooltip />
				<el-table-column prop="className" label="分类" :formatter="(row: any) => row.classNameFkDisplayName" show-overflow-tooltip />
				<el-table-column prop="workAreaId" label="区域" :formatter="(row: any) => row.workAreaFkDisplayName" show-overflow-tooltip />
				<el-table-column prop="team" label="劳务队" show-overflow-tooltip />
				<el-table-column prop="planStart" min-width="140" label="计划开工" show-overflow-tooltip>
					<template #default="scope">
						<div style="display: flex; align-items: center; gap: 8px;">
							<span>{{ formatDate(scope.row, null, scope.row.planStart) }}</span>
							<!-- 延期指示器 -->
							<el-popover
								v-if="Number(scope.row.startDelayDays) > 0"
								placement="top"
								:width="300"
								trigger="click"
							>
								<template #reference>
									<div
										style="
											background: #ff4d4f;
											color: white;
											border-radius: 50%;
											width: 20px;
											height: 20px;
											font-size: 11px;
											font-weight: bold;
											display: flex;
											align-items: center;
											justify-content: center;
											border: 1px solid white;
											box-shadow: 0 1px 4px rgba(255, 77, 79, 0.4);
											cursor: pointer;
											flex-shrink: 0;
										"
									>
										{{ scope.row.startDelayDays }}
									</div>
								</template>
								<div>
									<div style="margin-bottom: 10px; font-weight: bold;">开工延期原因</div>
									<el-input
										v-model="delayReasonEdit.start[scope.row.id]"
										type="textarea"
										:rows="3"
										placeholder="请输入:延期原因 | 预计时间"
										maxlength="500"
										show-word-limit
									/>
									<div style="margin-top: 10px; text-align: right;">
										<el-button size="small" @click="delayReasonEdit.start[scope.row.id] = scope.row.startDelayReason || ''">
											取消
										</el-button>
										<el-button size="small" type="primary" @click="updateDelayReason(scope.row.id, 'StartDelayReason', delayReasonEdit.start[scope.row.id] || '')">
											保存
										</el-button>
									</div>
								</div>
							</el-popover>
						</div>
					</template>
				</el-table-column>
				<el-table-column prop="planEnd" min-width="140" label="计划完工" show-overflow-tooltip>
					<template #default="scope">
						<div style="display: flex; align-items: center; gap: 8px;">
							<span>{{ formatDate(scope.row, null, scope.row.planEnd) }}</span>
							<!-- 延期指示器 -->
							<el-popover
								v-if="Number(scope.row.endDelayDays) > 0"
								placement="top"
								:width="300"
								trigger="click"
							>
								<template #reference>
									<div
										style="
											background: #ff4d4f;
											color: white;
											border-radius: 50%;
											width: 20px;
											height: 20px;
											font-size: 11px;
											font-weight: bold;
											display: flex;
											align-items: center;
											justify-content: center;
											border: 1px solid white;
											box-shadow: 0 1px 4px rgba(255, 77, 79, 0.4);
											cursor: pointer;
											flex-shrink: 0;
										"
									>
										{{ scope.row.endDelayDays }}
									</div>
								</template>
								<div>
									<div style="margin-bottom: 10px; font-weight: bold;">完工延期原因</div>
									<el-input
										v-model="delayReasonEdit.end[scope.row.id]"
										type="textarea"
										:rows="3"
										placeholder="请输入:延期原因 | 预计时间"
										maxlength="500"
										show-word-limit
									/>
									<div style="margin-top: 10px; text-align: right;">
										<el-button size="small" @click="delayReasonEdit.end[scope.row.id] = scope.row.endDelayReason || ''">
											取消
										</el-button>
										<el-button size="small" type="primary" @click="updateDelayReason(scope.row.id, 'EndDelayReason', delayReasonEdit.end[scope.row.id] || '')">
											保存
										</el-button>
									</div>
								</div>
							</el-popover>
						</div>
					</template>
				</el-table-column>
				<el-table-column prop="actualStart" min-width="120" label="实际开工" show-overflow-tooltip>
					<template #default="scope">
						<InlineEdit
							v-if="auth('planList:update')"
							:value="scope.row.actualStart ? formatDate(scope.row, null, scope.row.actualStart) : null"
							type="date"
							:loading="state.inlineEditLoading[`${scope.row.id}_actualStart`]"
							@confirm="(value) => updateInlineField(scope.row, 'actualStart', value)"
						/>
						<span v-else>{{ scope.row.actualStart ? formatDate(scope.row, null, scope.row.actualStart) : '' }}</span>
					</template>
				</el-table-column>
				<el-table-column prop="actualEnd" min-width="120" label="实际完工" show-overflow-tooltip>
					<template #default="scope">
						<InlineEdit
							v-if="auth('planList:update')"
							:value="scope.row.actualEnd ? formatDate(scope.row, null, scope.row.actualEnd) : null"
							type="date"
							:loading="state.inlineEditLoading[`${scope.row.id}_actualEnd`]"
							@confirm="(value) => updateInlineField(scope.row, 'actualEnd', value)"
						/>
						<span v-else>{{ scope.row.actualEnd ? formatDate(scope.row, null, scope.row.actualEnd) : '' }}</span>
					</template>
				</el-table-column>
				<el-table-column prop="remark" min-width="150" label="备注" show-overflow-tooltip>
					<template #default="scope">
						<InlineEdit
							v-if="auth('planList:update')"
							:value="scope.row.remark"
							type="text"
							placeholder="点击编辑备注"
							:max-length="128"
							:loading="state.inlineEditLoading[`${scope.row.id}_remark`]"
							@confirm="(value) => updateInlineField(scope.row, 'remark', value)"
						/>
						<span v-else>{{ scope.row.remark || '' }}</span>
					</template>
				</el-table-column>
				<el-table-column prop="status" label="状态" show-overflow-tooltip>
					<template #default="scope">
						<g-sys-dict v-model="scope.row.status" code="FinishStatusEnum" />
					</template>
				</el-table-column>
				<el-table-column label="操作" width="140" align="center" fixed="right" show-overflow-tooltip v-if="auth('planList:update') || auth('planList:delete')">
					<template #default="scope">
						<ModifyRecord size="small" text type="primary" :data="scope.row" />
						<!-- <el-button icon="ele-Edit" size="small" text type="primary" @click="editDialogRef.openDialog(scope.row, '编辑计划清单')" v-auth="'planList:update'"> 编辑 </el-button> -->
						<el-button icon="ele-Delete" size="small" text type="primary" @click="delPlanList(scope.row)" v-auth="'planList:delete'"> 删除 </el-button>
					</template>
				</el-table-column>
			</el-table>
			<el-pagination
				v-model:currentPage="state.tableParams.page"
				v-model:page-size="state.tableParams.pageSize"
				@size-change="(val: any) => handleQuery({ pageSize: val })"
				@current-change="(val: any) => handleQuery({ page: val })"
				layout="total, sizes, prev, pager, next, jumper"
				:page-sizes="[10, 20, 50, 100, 200, 500]"
				:total="state.tableParams.total"
				size="small"
				background
			/>
			<ImportData ref="importDataRef" :import="planListApi.importData" :download="planListApi.downloadTemplate" v-auth="'planList:import'" @refresh="handleQuery" />
			<printDialog ref="printDialogRef" :title="'打印计划清单'" @reloadTable="handleQuery" />
			<editDialog ref="editDialogRef" @reloadTable="handleQuery" />
		</el-card>
	</div>
</template>
<style scoped>
:deep(.el-input),
:deep(.el-select),
:deep(.el-input-number) {
	width: 100%;
}

</style>
